package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.VisitorService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorServiceImp implements VisitorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//查询最近访客
    public List<Visitor> findVisitorByCondition(Long userId, Long lastAccessTime) {
        //创建条件为用户id相同、访问时间大于上次登录时间、最近5条
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("date").gt(lastAccessTime))
                .skip(0).limit(5);
        //调用mongo查询出满足条件的访客
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        //返回结果
        return visitors;
    }

    @Override//添加访客
    public void addVisitor(Visitor visitor) {
        //创建条件为用户id相同和访客id相同的条件
        Query query = new Query(Criteria.where("userId").is(visitor.getUserId())
                .and("visitorUserId").is(visitor.getVisitorUserId()));
        //调用rpc查询是否有条件中记录
        if (mongoTemplate.exists(query, Visitor.class)) {
            //有的话 取出记录 对比两次来访时间
            Visitor visitor1 = mongoTemplate.findOne(query, Visitor.class);
            //如果大于一小时 保存一条新记录
            if ((visitor.getDate() - visitor1.getDate()) > 3600000) {
                mongoTemplate.save(visitor);
                //不大于一小时 保留之前记录 修改最新来访时间
            } else {
                visitor1.setDate(visitor.getDate());
                mongoTemplate.save(visitor1);
        }
    } else {//没有的话 添加访客记录
        mongoTemplate.save(visitor);
        }

    }
}
